//===============================================================================================
//
// (c) Copyright Microsoft Corporation.
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.
//
//===============================================================================================

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using MyWebPagesStarterKit;
using MyWebPagesStarterKit.Controls;
using MyWebPagesStarterKit.Providers;
using System.Xml;
using System.IO;
using System.Collections.Specialized;
using System.Collections.Generic;
using System.Web.Configuration;

public partial class Administration_Navigation : PageBaseClass
{
    private SitemapEditor editor = null;
    protected string lang;

    protected void Page_Load(object sender, EventArgs e)
    {
        //define language for the documentation path
        lang = System.Threading.Thread.CurrentThread.CurrentCulture.TwoLetterISOLanguageName;
        if (!File.Exists(HttpContext.Current.Server.MapPath(string.Format("~/Documentation/" + lang + "/quick_guide.html"))))
        {
            lang = "en";
        }
       
        if (!User.IsInRole(RoleNames.Administrators.ToString()))
            Response.Redirect("Login.aspx");

        Response.Expires = 0;
        Response.ExpiresAbsolute = DateTime.Now.AddMinutes(-1.0);
        Response.CacheControl = "private";
        Response.Cache.SetCacheability(HttpCacheability.NoCache);

        if (!IsPostBack)
        {
            btnDelete.OnClientClick = "if (!confirm('" + Resources.StringsRes.adm_Navigation_PageDeletionWarning + "')) return false;";
            populateList(SiteMap.RootNode, 0);

            if (Request.QueryString["sel"] != null)
            {
               
                lstPages.SelectedValue = Request.QueryString["sel"];
                showPageDetails(lstPages.SelectedValue);
            }
            else
            {
                // Binds roles list
                RolesList.DataSource = System.Web.Security.Roles.GetAllRoles();
                RolesList.DataBind();
                RolesList.Items.Insert(0,new ListItem("---------------",""));
              
            }
            drpMovePage.Visible = !string.IsNullOrEmpty(lstPages.SelectedValue);
            btnMovePage.Visible = !string.IsNullOrEmpty(lstPages.SelectedValue);
            LoadData();
        }
        LoadData();
    }

    protected void MovePageTo(object sender, EventArgs e)
    {
        if (string.IsNullOrEmpty(drpMovePage.SelectedValue))
            return;

        if (string.IsNullOrEmpty(lstPages.SelectedValue))
            return;

        SitemapEditor editor = new SitemapEditor();
        editor.InsertPageAt(lstPages.SelectedValue, drpMovePage.SelectedValue);
        editor.Save();
        
        Response.Redirect(string.Format("{0}?sel={1}", Request.Url.AbsolutePath, lstPages.SelectedValue));
    }

    private void populateMoveLinks(SiteMapNode parentNode, int level)
    {
        foreach (SiteMapNode node in parentNode.ChildNodes)
        {
            if (node["pageId"] != null)
            {
                string title = node.Title;
                for (int i = 0; i < level; i++)
                    title = "..." + title;
                if (node["visible"] == false.ToString())
                    title += " (invisible)";
                if (node["pageId"] == _website.HomepageId)
                    title += " (Homepage)";
                drpMovePage.Items.Add(new ListItem(title, node["pageId"]));
                populateMoveLinks(node, level + 1);
            }
        }
    }

    /// <summary>
    /// Enable use of other Themes
    /// </summary>
    private void LoadThemes()
    {
        if (!string.IsNullOrEmpty(lstPages.SelectedValue))
        {
            WebPage page = new WebPage(lstPages.SelectedValue);
            foreach (string dir in Directory.GetDirectories(Server.MapPath("~/App_Themes")))
            {
                if (Path.GetFileName(dir) != "Admin")
                {
                    ListItem item = new ListItem(Path.GetFileName(dir), Path.GetFileName(dir));

                    if (Path.GetFileName(dir) == page.Theme)
                        item.Selected = true;

                    drpThemes.Items.Add(item);
                }
            }
            drpThemes.Items.Insert(0, new ListItem(Resources.StringsRes.clt_UseDefaultWebsiteTheme, ""));
        }
    }

    protected void ChangeTheme(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(lstPages.SelectedValue))
        {
            WebPage page = new WebPage(lstPages.SelectedValue);

            if (!string.IsNullOrEmpty(drpThemes.SelectedValue))
            {
                page.Theme = drpThemes.SelectedValue;
                page.SaveData();
            }
            else
            {
                page.Theme = string.Empty;
                page.SaveData();
            }
            drpThemes.Items.Clear();
            LoadThemes();
            drpTemplates.Items.Clear();
            LoadTemplates();
        }
    }

    private void LoadTemplates()
    {
        if (!string.IsNullOrEmpty(lstPages.SelectedValue))
        {
            WebPage page = new WebPage(lstPages.SelectedValue);
            XmlDocument xml = new XmlDocument();
            xml.Load(Server.MapPath("~/web.config"));
            XmlNode root = xml.SelectSingleNode("configuration/templates/themes");

            string theme = WebSite.GetInstance().Theme;

            if (!string.IsNullOrEmpty(page.Theme))
                theme = page.Theme;

            if (root.HasChildNodes)
            {
                foreach (XmlNode node in root.ChildNodes)
                {
                    if (theme.ToLower().Equals(node.Attributes["name"].Value.ToLower()))
                    {
                        ListItem item = new ListItem(node.Attributes["template"].Value, node.Attributes["template"].Value);
                        if (node.Attributes["template"].Value.ToLower() == page.TemplateName.ToLower())
                            item.Selected = true;

                        drpTemplates.Items.Add(item);
                    }
                }
            }
        }
    }

    protected void valVirtualPath_ServerValidate(object source, ServerValidateEventArgs args)
    {
        string virtualPath = txtVirtualPath.Text.Trim();

        virtualPath = TextFormatter.CreateFriendlyUrl(virtualPath);

        if (virtualPath != string.Empty)
        {
            if (editor == null)
                editor = new SitemapEditor();

            if (!virtualPath.StartsWith("~/"))
            {
                if (virtualPath.StartsWith("/"))
                    virtualPath = virtualPath.Substring(1);
                virtualPath = "~/" + virtualPath;
            }
            if (!virtualPath.EndsWith(".aspx"))
            {
                    virtualPath += ".aspx";
            }
            virtualPath = virtualPath.Replace(' ', '-');
            txtVirtualPath.Text = virtualPath;

            XmlNode node = editor.FindNodeByVirtualPath(virtualPath.ToLower());
            if (
                (node != null) 
                && 
                (
                    (node.Attributes["pageId"] == null) 
                    ||
                    (node.Attributes["pageId"].Value != lstPages.SelectedValue)
                )
            )
                args.IsValid = false;
            else
                args.IsValid = true;
        }
        else
        {
            args.IsValid = true;
        }
    }

    private void populateList(SiteMapNode parentNode, int level)
    {
        foreach (SiteMapNode node in parentNode.ChildNodes)
        {
            if (node["pageId"] != null)
            {
                string title = node.Title;
                for (int i = 0; i < level; i++)
                    title = "..." + title;
                if (node["visible"] == false.ToString())
                    title += " (invisible)";
                if (node["pageId"] == _website.HomepageId)
                    title += " (Homepage)";

                lstPages.Items.Add(new ListItem(title, node["pageId"]));
                populateList(node, level + 1);
            }
        }
    }


    private void populateLinkTo(SiteMapNode parentNode, int level)
    {
        foreach (SiteMapNode node in parentNode.ChildNodes)
        {
            if (node["pageId"] != null)
            {
                string title = node.Title;
                for (int i = 0; i < level; i++)
                    title = "..." + title;
                if (node["visible"] == false.ToString())
                    title += " (invisible)";
                if (node["pageId"] == _website.HomepageId)
                    title += " (Homepage)";
                drpLinkedTo.Items.Add(new ListItem(title, node["pageId"]));
                populateLinkTo(node, level + 1);
            }
        }
    }


    protected void btnSave_Click(object sender, EventArgs e)
    {
        Validate();
        if (IsValid)
        {
            WebPage page = new WebPage(lstPages.SelectedValue);

            /* SEO Tags */
            page.Title = txtTitle.Text.Trim();
            page.Description = txtDescription.Text.Trim();
            page.Keywords = txtKeywords.Text.Trim(); 

            page.NavigationName = txtNavigation.Text.Trim();
            page.Visible = chkVisible.Checked;
            page.AllowAnonymousAccess = chkAnonymousAccess.Checked;
            page.EditPowerUser = chkEditPowerUser.Checked; // (PowerUser Management)
            page.Hidden = chkHidden.Checked;
            page.HeaderImage = txtImage.Value;
            

            string virtualPath = txtVirtualPath.Text.Trim().ToLower();
            virtualPath = TextFormatter.CreateFriendlyUrl(virtualPath);

            if (virtualPath != string.Empty)
            {
                if (!virtualPath.StartsWith("~/"))
                {
                    if (virtualPath.StartsWith("/"))
                        virtualPath = virtualPath.Substring(1);
                    virtualPath = "~/" + virtualPath;
                }
                if (!virtualPath.EndsWith(".aspx"))
                {
                    virtualPath += ".aspx";
                }

                virtualPath = virtualPath.Replace(' ', '_');
                virtualPath = virtualPath.Replace("~/.aspx", "~/"); //Homepage
            }
            page.VirtualPath = virtualPath;
            txtVirtualPath.Text = virtualPath;
            page.TemplateName = drpTemplates.SelectedValue;

           
            page.Redirect301 = txtRedirect301.Text;
            page.SaveData();

            if (!string.IsNullOrEmpty(drpLinkedTo.SelectedValue))
                page.LinkedToPage = drpLinkedTo.SelectedValue;
            else
                page.LinkedToPage = string.Empty;

            if (editor == null)
                editor = new SitemapEditor();

            List<string> roles = new List<string>();
            foreach (ListItem item in RolesList.Items)
                roles.Add(item.Text);

            editor.UpdatePage(page,roles);

            List<string> RoleList = new List<string>();
            if (page.AllowAnonymousAccess)
            {
                RoleList.Add("*");
            }
            else
            {
                foreach (ListItem CurRole in RolesList.Items)
                    if (CurRole.Selected && CurRole.Value!=string.Empty)
                        RoleList.Add(CurRole.Text);
            }

            editor.UpdatePage(page, RoleList);
            editor.Save();

            Response.Redirect(string.Format("{0}?sel={1}", Request.Url.AbsolutePath, lstPages.SelectedValue));
        }
    }

    protected void btnSetHomepage_Click(object sender, EventArgs e)
    {
        WebPage page = new WebPage(lstPages.SelectedValue);

        page.AllowAnonymousAccess = true;
        page.Visible = true;
        page.SaveData();
        _website.HomepageId = lstPages.SelectedValue;
        _website.SaveData();

        Response.Redirect(Request.RawUrl);
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        Sidebar.GetInstance().RemoveSection(lstPages.SelectedValue);
        WebPage page = new WebPage(lstPages.SelectedValue);
        page.Delete();
        SitemapEditor editor = new SitemapEditor();
        editor.DeletePage(lstPages.SelectedValue);
        editor.Save();
       

        Response.Redirect(Request.Url.AbsolutePath);
    }

    protected void movePage_Command(object sender, CommandEventArgs e)
    {
        SitemapEditor editor = new SitemapEditor();
        switch (e.CommandName)
        {
            case "up":
                editor.MoveUp(lstPages.SelectedValue);
                break;
            case "down":
                editor.MoveDown(lstPages.SelectedValue);
                break;
            case "left":
                editor.MoveLevelUp(lstPages.SelectedValue);
                break;
            case "right":
                editor.MoveLevelDown(lstPages.SelectedValue);
                break;
        }
        editor.Save();

        Response.Redirect(string.Format("{0}?sel={1}", Request.Url.AbsolutePath, lstPages.SelectedValue));
    }

    protected void btnNewPage_Click(object sender, EventArgs e)
    {
        string PageId = lstPages.SelectedValue;

        WebPage page = new WebPage();
        page.NavigationName = Resources.StringsRes.adm_Navigation_NewPageDefaultName;
        page.AllowAnonymousAccess = true;
        page.Visible = true;
        page.Hidden = false;
        page.SaveData();

        SitemapEditor editor = new SitemapEditor();
        editor.InsertPage(page, PageId);
        editor.Save();

        Response.Redirect(string.Format("{0}?sel={1}", Request.Url.AbsolutePath, page.PageId));
    }

    protected void lstPages_SelectedIndexChanged(object sender, EventArgs e)
    {
        showPageDetails(lstPages.SelectedValue);
    }



    private void showPageDetails(string pageId)
    {
        WebPage page = new WebPage(pageId);
        txtTitle.Text = page.Title;
        txtDescription.Text = page.Description;
        txtKeywords.Text = page.Keywords; 
        txtNavigation.Text = page.NavigationName;
        txtVirtualPath.Text = page.VirtualPath;
        chkVisible.Checked = page.Visible;
        chkAnonymousAccess.Checked = page.AllowAnonymousAccess;
        chkEditPowerUser.Checked = page.EditPowerUser; // (PowerUser Management)
        chkHidden.Checked = page.Hidden;
 
        bool isHomepage = (pageId == _website.HomepageId);
        chkVisible.Enabled = !isHomepage;
        chkAnonymousAccess.Enabled = !isHomepage;
        btnSetHomepage.Visible = !isHomepage;
        txtRedirect301.Text = page.Redirect301;
        txtImage.Value = page.HeaderImage;

        drpMovePage.Visible = true;
        btnMovePage.Visible = true;

        drpMovePage.Items.Clear();
        populateMoveLinks(SiteMap.RootNode, 0);

        drpThemes.Items.Clear();
        LoadThemes();

        drpTemplates.Items.Clear();
        LoadTemplates();


        if (!string.IsNullOrEmpty(page.TemplateName) && (drpTemplates.Items.FindByValue(page.TemplateName)!=null) )
            drpTemplates.SelectedValue = page.TemplateName;

        drpLinkedTo.Items.Clear();
        populateLinkTo(SiteMap.RootNode, 0);
        drpLinkedTo.Items.Insert(0, new ListItem("--------------------", ""));

        drpLinkedTo.SelectedValue = page.LinkedToPage;

        SitemapEditor editor = new SitemapEditor();
        btnDelete.Visible =
            (
                (lstPages.Items.Count > 1)
                &&
                (pageId != _website.HomepageId)
                &&
                (!editor.HasChildNodes(pageId))
            );

        // Binds roles list
        RolesList.Items.Clear();
        RolesList.DataSource = System.Web.Security.Roles.GetAllRoles();
        RolesList.DataBind();
        RolesList.Items.Remove(RolesList.Items.FindByText("Administrators"));
        RolesList.Items.Insert(0, new ListItem("---------------", ""));

        SiteMapNode MapNode = System.Web.SiteMap.Provider.FindSiteMapNode(page.VirtualPath);
        if (MapNode != null)
        {
            ArrayList NodeRoles;
            if (MapNode.Roles != null)
            {
                NodeRoles = (ArrayList)MapNode.Roles;
                // Initializes select roles
                foreach (ListItem CurRole in RolesList.Items)
                {
                    foreach (string Role in NodeRoles)
                    {
                        if (CurRole.Value.Equals(Role))
                            CurRole.Selected = true;
                    }
                }
            }
        }
        LocalizeMoveTitle.Visible = true;
        tblPageDetails.Visible = true;
        tblMoveIcons.Visible = true;

    }

    protected void CheckMinimumRoles(object source, ServerValidateEventArgs args)
    {
        if (RolesList.SelectedIndex == -1)
            args.IsValid = true;
    }

    protected void CopyData(object sender, EventArgs e)
    {
        string text = txtTitle.Text;
        txtVirtualPath.Text = text;
        txtNavigation.Text = text;
        txtDescription.Text = text;
        txtKeywords.Text = text;
    }

    protected void GotoPage(object sender, EventArgs e)
    {
        if (!string.IsNullOrEmpty(lstPages.SelectedValue))
        {
            WebPage page = new WebPage(lstPages.SelectedValue);
            Response.Redirect(page.VirtualPath);
        }
    }


    #region headerImages

    private string path;
    private void LoadData()
    {
        path = Server.MapPath("~/App_Data/UserImages/Image/HeaderImages/");
        images.DataSource = null;

        if (!Directory.Exists(path))
            Directory.CreateDirectory(path);

        List<ImgItem> img = new List<ImgItem>();
        foreach (string file in Directory.GetFiles(path))
        {
            ImgItem item = new ImgItem(Path.GetFileName(file), Path.GetFileName(file));
            img.Add(item);
        }

        images.DataSource = img;
        images.DataBind();
    }

    public string IsSelected(string fname)
    {
        if (fname.Equals(txtImage.Value))
            return "border: 1px solid green;";
        else
            return "border: 1px solid #eee;";
    }

    protected void Action(object sender, CommandEventArgs e)
    {
        if (!string.IsNullOrEmpty(e.CommandName))
        {
            string path = Server.MapPath("~/App_Data/UserImages/Image/HeaderImages/" + e.CommandName);
            if(File.Exists(path))
                File.Delete(path);
            LoadData();
        }
    }

    public class ImgItem
    {
        private string _ID;
        private string _ImageUrl;
        private string _FileName;

        public ImgItem(string id, string imageUrl)
        {
            this._ID = id;
            this._FileName = imageUrl;
            this._ImageUrl = imageUrl;
        }

        public string ID
        {
            get { return this._ID; }
            set { this._ID = value; }
        }

        public string FileName
        {
            get { return _FileName; }
            set { _FileName = value; }
        }

        public string ImageUrl
        {
            get { return "~/App_Data/UserImages/Image/HeaderImages/" + _ImageUrl; }
            set { _ImageUrl = value; }
        }

    }


    protected void Upload(object sender, EventArgs e)
    {
        if (fileupload.HasFile)
        {
            path = Server.MapPath("~/App_Data/UserImages/Image/HeaderImages/");

            // Get a reference to PostedFile object
            HttpPostedFile myFile = fileupload.PostedFile;

            // Get size of uploaded file
            int nFileLen = myFile.ContentLength;

            // make sure the size of the file is > 0
            if (nFileLen > 0)
            {
                // Allocate a buffer for reading of the file
                byte[] myData = new byte[nFileLen];

                // Read uploaded file from the Stream
                myFile.InputStream.Read(myData, 0, nFileLen);

                // Create a name for the file to store
                string strFilename = Path.GetFileName(myFile.FileName);

                //Create dir if not exist
                if (!Directory.Exists(path))
                    Directory.CreateDirectory(path);

                // Write data into a file
                WriteToFile(strFilename, path + strFilename, ref myData);
               
            }
        }
    }

    // Writes file to current folder
    private void WriteToFile(string strFilename, string strPath, ref byte[] Buffer)
    {
        // Create a file
        FileStream newFile = new FileStream(strPath, FileMode.Create);

        // Write data to the file
        newFile.Write(Buffer, 0, Buffer.Length);

        // Close file
        newFile.Close();
        txtImage.Value = strFilename;
        WebPage page = new WebPage(lstPages.SelectedValue);
        page.HeaderImage = strFilename;
        page.SaveData();
        
        LoadData();
    }

    #endregion

}
